package com.moyu.shopapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moyu.shopapp.entity.User;
import com.moyu.shopapp.mapper.UserMapper;
import com.moyu.shopapp.service.UserService;
import com.moyu.shopapp.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

/**
 * @author ZJF
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2023-12-01 16:32:18
 */

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    /**
     * 注册
     * @param user
     * @return
     */
    @Override
    public String register(User user) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, user.getUsername()); // 根据用户名查询
        //判断数据库中是否已存在该用户（True:进行注册,False:注册失败）
        if (userMapper.selectOne(lambdaQueryWrapper)==null){
            userMapper.insert(user);
            return "注册成功";
        }
        else {
            return "注册失败，该用户已存在";
        }
    }

    /**
     * 登录
     * @param user
     * @return
     */
    @Override
    public String login(User user) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, user.getUsername()) // 根据用户名查询
            .eq(User::getPassword, user.getPassword()); // 根据密码查询
        //判断是否存在该用户且密码是否正确
        if (userMapper.selectOne(lambdaQueryWrapper)!=null){
            String token=JwtUtils.generateJwt(user.getUsername());
            return token;
        }
        else{
            return "登录失败";
        }
    }

    @Override
    public String forget(User user) {
        //userMapper.updateById()
        return null;
    }

    /**
     * 获取用户数据
     * @param token
     * @return
     */
    @Override
    public User getUserInfo(String token) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername,JwtUtils.parseJwt(token));
        return userMapper.selectOne(lambdaQueryWrapper);
    }


}
